<?php


namespace App\Shuixing\Controllers;


use App\Models\Posts\WxComment;
use App\Models\Posts\WxLike;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsImg;
use App\Models\Posts\WxPostsTag;
use App\Models\Posts\WxPostsVideo;
use App\Models\Posts\WxTag;
use App\Models\Posts\WxUserCircle;
use App\Models\WxCircle;
use App\Models\WxUser;
use App\Models\WxUserFollow;

class CirclesController
{
    public function index($id, $limit = 5)
    {

        $circle = WxCircle::where('id', $id)
            ->first();
        $circle->user_count = WxUserCircle::where('circle_id', $circle->id)->count();
        $circle->posts_count = WxPost::where('circle_id', $circle->id)->count();
        $userIds = WxUserCircle::where('circle_id', $circle->id)->pluck('user_id');
        $circle->user = WxUser::whereIn('id', $userIds)->get(['id', 'user_name', 'user_avatar']);

        $circle_user = WxUser::where('id', $circle->user_id)
            ->first(['id', 'user_name', 'user_avatar', 'user_introduce']);
        $circle_user->like_count = WxLike::where('user_id', $circle->user_id)->count();
        $circle_user->fans_count = WxUserFollow::where('user_follow_id', $circle->user_id)->count();

        $newdata = WxPost::where('circle_id', $id)
            ->where('is_examine', 1)
            ->where('posts_state', 0)
            ->orderBy('id', 'desc')
            ->limit(5)->get();
        $newdata = self::postsParame($newdata);//文章详情

        $data = WxPost::where('circle_id', $id)
            ->where('is_examine', 1)
            ->where('posts_state', 0)
            ->orderBy('is_sticky', 'desc')
            ->orderBy('id', 'desc')
            ->paginate($limit);
        $data = self::postsParame($data);//文章详情


        return view('shuixing/circles', ['data' => $data, 'newdata' => $newdata, 'circle' => $circle, 'circle_user' => $circle_user]);
    }

    public static function postsParame($data)
    {
        $data->map(function ($v) {
            $v->user = WxUser::where('id', $v->user_id)
                ->first(['user_avatar', 'user_name', 'id', 'is_member', 'is_official', 'is_authentication']);//发帖人
            $tagsIds = WxPostsTag::where('posts_id', $v->id)->pluck('tags_id');//标签ID列表
            $v->tags = WxTag::whereIn('id', $tagsIds)->get(['tags_name', 'id']);//标签列表
            $v->like_count = WxLike::where('posts_id', $v->id)->count(); // 帖子喜欢数量
            $v->comment_count = WxComment::where(['posts_id' => $v->id, 'comment_state' => 1])->count(); // 评论数量
            $v->image = WxPostsImg::where('posts_id', $v->id)->value('img_url'); // 帖子图片
            $v->vimage = WxPostsVideo::where('posts_id', $v->id)->value('video_thumb_url'); // 帖子视频封面
            $v->format_time = format_datetime($v->created_at); // 发帖时间
        });

        return $data;
    }
}
